//! # 配置管理示例
//!
//! 演示如何使用 RustCloud 配置管理功能
//!
//! ## 运行方式
//!
//! ```bash
//! cargo run --example config_server
//! ```
//!
//! ## 功能演示
//!
//! 这个示例展示了 RustCloud 配置模块的核心功能：
//!
//! * 配置文件加载（TOML、YAML、JSON）
//! * 配置验证和类型安全
//! * 配置管理器和热加载
//! * 多源配置合并

use std::time::Duration;
use tracing::{info, warn, error, Level};
use tracing_subscriber;

use rustcloud_config::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // 初始化日志
    tracing_subscriber::fmt()
        .with_max_level(Level::INFO)
        .init();

    info!("🚀 启动RustCloud配置管理示例...");

    // 创建示例配置文件
    create_example_configs().await?;

    // 演示基本配置加载
    demo_basic_config_loading().await?;

    // 演示配置管理器
    demo_config_manager().await?;

    // 演示多源配置合并
    demo_multi_source_config().await?;

    // 演示配置验证
    demo_config_validation().await?;

    // 演示热加载（模拟）
    demo_hot_reload().await?;

    info!("✅ 配置管理示例完成");
    Ok(())
}

/// 创建示例配置文件
async fn create_example_configs() -> Result<(), Box<dyn std::error::Error>> {
    use std::fs;

    // 确保配置目录存在
    fs::create_dir_all("./examples-config")?;

    // 创建TOML配置文件
    let toml_config = r#"
[application]
name = "user-service"
version = "1.0.0"
port = 8080
description = "用户管理服务"

[application.metadata]
env = "development"
team = "microservices"

[registry]
registry_type = "nacos"
server_addr = "127.0.0.1:8848"
namespace = "production"
group = "microservices"

[loadbalancer]
strategy = "round_robin"
health_check_enabled = true

[circuit_breaker]
enabled = false
failure_threshold = 5
recovery_timeout = 30
half_open_max_calls = 10

[transport]
timeout = 5000
retries = 3
retry_delay = 1000
max_connections = 100
keep_alive = true

[logging]
level = "info"
format = "plain"
output = "console"
file_path = ""
console_output = true

[gateway]
server_addr = "0.0.0.0:8080"

[gateway.filters.auth]
enabled = false
api_keys = {}

[gateway.filters.rate_limit]
enabled = false
max_requests = 100
window_duration = 60

[gateway.filters.logging]
enabled = true
log_level = "info"

[[gateway.routes]]
path_prefix = "/api/v1/users"
service_name = "user-service"
rewrite_path = true
enable_cache = true
cache_ttl = 300
"#;
    fs::write("./examples-config/application.toml", toml_config)?;

    // 创建YAML配置文件
    let yaml_config = r#"
application:
  name: "order-service"
  version: "2.0.0"
  port: 8081
  description: "订单管理服务"
  metadata:
    env: "development"
    team: "ecommerce"

registry:
  registry_type: "consul"
  server_addr: "127.0.0.1:8500"
  namespace: "development"
  group: "ecommerce"

loadbalancer:
  strategy: "random"
  health_check_enabled: true

circuit_breaker:
  enabled: false
  failure_threshold: 5
  recovery_timeout: 30
  half_open_max_calls: 10

transport:
  timeout: 5000
  retries: 3
  retry_delay: 1000
  max_connections: 100
  keep_alive: true

logging:
  level: "info"
  format: "json"
  output: "console"
  file_path: ""
  console_output: true

gateway:
  server_addr: "0.0.0.0:8081"
  filters:
    auth:
      enabled: false
      api_keys: {}
    rate_limit:
      enabled: false
      max_requests: 100
      window_duration: 60
    logging:
      enabled: true
      log_level: "info"
  routes:
    - path_prefix: "/api/v1/orders"
      service_name: "order-service"
      rewrite_path: true
      enable_cache: false
      cache_ttl: 60
"#;
    fs::write("./examples-config/application.yaml", yaml_config)?;

    // 创建JSON配置文件
    let json_config = r#"{
  "application": {
    "name": "payment-service",
    "version": "1.5.0",
    "port": 8082,
    "description": "支付服务",
    "metadata": {
      "env": "production",
      "team": "payment"
    }
  },
  "registry": {
    "registry_type": "eureka",
    "server_addr": "127.0.0.1:8761",
    "namespace": "production",
    "group": "payment"
  },
  "loadbalancer": {
    "strategy": "consistent_hash",
    "health_check_enabled": true
  },
  "circuit_breaker": {
    "enabled": false,
    "failure_threshold": 5,
    "recovery_timeout": 30,
    "half_open_max_calls": 10
  },
  "transport": {
    "timeout": 5000,
    "retries": 3,
    "retry_delay": 1000,
    "max_connections": 100,
    "keep_alive": true
  },
  "logging": {
    "level": "info",
    "format": "json",
    "output": "file",
    "file_path": "/logs/app.log",
    "console_output": true
  },
  "gateway": {
    "server_addr": "0.0.0.0:8082",
    "filters": {
      "auth": {
        "enabled": false,
        "api_keys": {}
      },
      "rate_limit": {
        "enabled": false,
        "max_requests": 100,
        "window_duration": 60
      },
      "logging": {
        "enabled": true,
        "log_level": "info"
      }
    },
    "routes": [
      {
        "path_prefix": "/api/v1/payments",
        "service_name": "payment-service",
        "rewrite_path": true,
        "enable_cache": true,
        "cache_ttl": 600
      }
    ]
  }
}"#;
    fs::write("./examples-config/application.json", json_config)?;

    info!("📝 示例配置文件已创建:");
    info!("   - application.toml (TOML格式)");
    info!("   - application.yaml (YAML格式)");
    info!("   - application.json (JSON格式)");

    Ok(())
}

/// 演示基本配置加载
async fn demo_basic_config_loading() -> Result<(), Box<dyn std::error::Error>> {
    info!("📖 演示基本配置加载...");

    // 加载TOML配置
    match RustCloudConfig::from_file("./examples-config/application.toml") {
        Ok(config) => {
            info!("✅ TOML配置加载成功:");
            info!("   应用名称: {}", config.application.name);
            info!("   版本: {}", config.application.version);
            info!("   端口: {}", config.application.port);
        }
        Err(e) => error!("❌ TOML配置加载失败: {}", e),
    }

    // 加载YAML配置
    match RustCloudConfig::from_file("./examples-config/application.yaml") {
        Ok(config) => {
            info!("✅ YAML配置加载成功:");
            info!("   应用名称: {}", config.application.name);
            info!("   注册中心: {}", config.registry.registry_type);
        }
        Err(e) => error!("❌ YAML配置加载失败: {}", e),
    }

    // 加载JSON配置
    match RustCloudConfig::from_file("./examples-config/application.json") {
        Ok(config) => {
            info!("✅ JSON配置加载成功:");
            info!("   应用名称: {}", config.application.name);
            info!("   服务地址: {}", config.gateway.server_addr);
        }
        Err(e) => error!("❌ JSON配置加载失败: {}", e),
    }

    Ok(())
}

/// 演示配置管理器
async fn demo_config_manager() -> Result<(), Box<dyn std::error::Error>> {
    info!("🔧 演示配置管理器...");

    // 创建配置管理器
    let (mut manager, _receiver) = ConfigManagerBuilder::new()
        .add_source(ConfigSource::File {
            path: "./examples-config/application.toml".to_string(),
            format: ConfigFormat::Toml,
        })
        .add_source(ConfigSource::File {
            path: "./examples-config/application.yaml".to_string(),
            format: ConfigFormat::Yaml,
        })
        .reload_interval(Duration::from_secs(5))
        .build().await?;

    // 加载配置
    match manager.load_config().await {
        Ok(config) => {
            info!("✅ 配置管理器加载成功:");
            info!("   合并后的应用名称: {}", config.application.name);
            info!("   注册中心类型: {}", config.registry.registry_type);
        }
        Err(e) => error!("❌ 配置管理器加载失败: {}", e),
    }

    Ok(())
}

/// 演示多源配置合并
async fn demo_multi_source_config() -> Result<(), Box<dyn std::error::Error>> {
    info!("🔀 演示多源配置合并...");

    // 创建多个配置源
    let base_source = ConfigSource::File {
        path: "./examples-config/application.toml".to_string(),
        format: ConfigFormat::Toml,
    };
    let override_source = ConfigSource::File {
        path: "./examples-config/application.yaml".to_string(),
        format: ConfigFormat::Yaml,
    };

    // 创建配置管理器并合并配置
    let (mut manager, _) = ConfigManagerBuilder::new()
        .add_source(base_source)
        .add_source(override_source)
        .build().await?;

    match manager.load_config().await {
        Ok(config) => {
            info!("✅ 多源配置合并成功:");
            info!("   应用名称: {} (来自YAML，覆盖TOML)", config.application.name);
            info!("   应用端口: {} (来自TOML，YAML未覆盖)", config.application.port);
        }
        Err(e) => error!("❌ 多源配置合并失败: {}", e),
    }

    Ok(())
}

/// 演示配置验证
async fn demo_config_validation() -> Result<(), Box<dyn std::error::Error>> {
    info!("✅ 演示配置验证...");

    match RustCloudConfig::from_file("./examples-config/application.toml") {
        Ok(config) => {
            match config.validate() {
                Ok(_) => info!("✅ 配置验证通过"),
                Err(e) => warn!("⚠️ 配置验证失败: {}", e),
            }
        }
        Err(e) => error!("❌ 配置加载失败: {}", e),
    }

    Ok(())
}

/// 演示热加载（模拟）
async fn demo_hot_reload() -> Result<(), Box<dyn std::error::Error>> {
    info!("🔄 演示配置热加载（模拟）...");

    let (mut manager, mut receiver) = ConfigManagerBuilder::new()
        .add_source(ConfigSource::File {
            path: "./examples-config/application.toml".to_string(),
            format: ConfigFormat::Toml,
        })
        .reload_interval(Duration::from_millis(100))
        .build().await?;

    // 启动热加载
    manager.start_hot_reload().await;

    // 启动监听任务
    let handle = tokio::spawn(async move {
        if let Ok(config) = receiver.changed().await {
            info!("📨 接收到配置变更事件");
        }
    });

    // 模拟配置变更检测
    tokio::time::sleep(Duration::from_millis(50)).await;
    info!("✅ 热加载监听已启动");

    // 停止监听
    handle.abort();
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_create_example_configs() {
        if let Err(e) = create_example_configs().await {
            eprintln!("创建示例配置失败: {}", e);
        }
    }

    #[tokio::test]
    async fn test_basic_config_loading() {
        create_example_configs().await.unwrap();
        demo_basic_config_loading().await.unwrap();
    }
}